package com.summer.data.rs.map;

import com.summer.data.dialect.Dialect;
import com.summer.data.exception.BaseException;
import com.summer.data.table.BaseColumn;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 345480567@qq.com
 */

public class ResultSetToDtoFun<T> extends AbstractResultSetMapFun<T> {

    Class<T> clazz;

    public ResultSetToDtoFun(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public T map(ResultSet resultSet, Dialect dialect) {
        try {
            T t = clazz.newInstance();

            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {

                // 字段名称
                String columnName = BaseColumn.getFieldColumnName(field);

                Integer index = getColumnIndex(resultSet, columnName, dialect);
                if (index == null) {
                    continue;
                }

                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                Object attr = field.get(t);

                Object valueObj = resultSet.getObject(index);
                if (valueObj == null) {
                    field.set(t, null);
                } else {
                    if (attr instanceof BaseColumn) {
                        BaseColumn col = (BaseColumn) attr;
                        col.fetchNotNullValue(resultSet, index);
                    } else {
                        helpFetchNotNull(resultSet, index, t, field);
                    }
                }

//                // 非 Column 的不处理
//                if (BaseColumn.class.isAssignableFrom(field.getType())) {
//                } else {
//
//                    ResultSetMetaData metaData = resultSet.getMetaData();
//
//                    for(Integer i=1; i<=metaData.getColumnCount(); i++) {
//                        String label = metaData.getColumnLabel(i);
//                        Object val = resultSet.getObject(i);
//                        rowMap.put(label, val);
//                    }
//                }


            }

            return t;
        } catch (InstantiationException e) {
            throw new BaseException(e);
        } catch (IllegalAccessException e) {
            throw new BaseException(e);
        } catch (SQLException e) {
            throw new BaseException(e);
        }
    }

}
